package com.harvey.metrics.metric.gauge;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.harvey.metrics.metric.BaseExample;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author harvey
 * @Description
 * @date 2020-04-08 17:25
 * @since
 */

public class RatioGaugeExample extends BaseExample {

    private static final MetricRegistry registry = new MetricRegistry();

    private static final ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    private static final Meter totalMeter = new Meter();
    private static final Meter successMeter = new Meter();

    public static void main(String[] args) {

        reporter.start(3, TimeUnit.SECONDS);

        registry.gauge(MetricRegistry.name(RatioGaugeExample.class, "ratio"), () -> new RatioGauge() {
            @Override
            protected Ratio getRatio() {
                // 计算占比率
                return Ratio.of(successMeter.getCount(), totalMeter.getCount());
            }
        });

        for (; ; ) {
            business();
            randomSleep();
        }


    }


    private static void business() {
        // total inc
        totalMeter.mark();
        try {
            int x = 10 / ThreadLocalRandom.current().nextInt(6);

            // success inc
            successMeter.mark();

        } catch (Exception e) {
            System.out.println("ERROR");
        }
    }
}
